package com.whz.generic.serializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.whz.generic.json.JacksonUtils;
import lombok.SneakyThrows;

import java.util.Arrays;

/**
 * JackJson 序列化方式
 *
 * @author whz
 */
public class JacksonRedisSerializer extends AbstractRedisSerializer {

    private static final ObjectMapper OBJECT_MAPPER = JacksonUtils.createDefaultObjectMapper();

    static {
        OBJECT_MAPPER.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        OBJECT_MAPPER.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        OBJECT_MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    }

    @SneakyThrows
    @Override
    public byte[] serialize(Object value) {
        if (value == null) {
            return SerializationUtils.EMPTY_ARRAY;
        }
        return OBJECT_MAPPER.writeValueAsBytes(value);
    }

    @SneakyThrows
    @Override
    public Object deserialize(byte[] bytes) {
        if (SerializationUtils.isEmpty(bytes)) {
            return null;
        }
        if (Arrays.equals(getNullValueBytes(), bytes)) {
            return null;
        }
        return OBJECT_MAPPER.readValue(bytes, Object.class);

    }
}